import {
  getAppointments,
  createCourseAppointment,
  updateCourseAppointmentStatus,
  addCourseAppointmentAssistantCoach,
  addCourseAppointmentClient,
  addCourseAppointmentPackage,
  removeCourseAppointmentPackage,
  removeCourseAppointmentAssistantCoach,
  removeCourseAppointmentClient
} from "@/lib/appointmentService";
import { getCoursePackages } from "@/lib/coursePackagesService";
import { STATUS } from "@/consts";
import { getAllUsers } from "@/lib/userService";
import { getCampuses } from "@/lib/campusService";
import { getCourts } from "@/lib/courtsService";
import {deductCoursePackageClasses} from '@/lib/coursePackagesService'
import { formatDateForAPI } from '@/lib/dateUtils'
import Client from "./Client";

export default async function AppointmentManagerPage() {
  const campuses = await getCampuses({});

  const listAppointments = async ({
    appointment_id,
    coach_id,
    branch_campus_id,
    court_id,
    status,
    start_time_from,
    start_time_to,
  }) => {
    "use server";
    console.log(
      coach_id,
      branch_campus_id,
      court_id,
      status,
      start_time_from,
      start_time_to
    );
    try {
      const appointments = await getAppointments({
        coach_id,
        branch_campus_id,
        court_id,
        status,
        start_time_from: formatDateForAPI(start_time_from),
        start_time_to: formatDateForAPI(start_time_to),
      });
      const filtered = appointment_id ? appointments.filter(a => String(a.id) === String(appointment_id)) : appointments;
      return filtered;
    } catch (error) {
      console.error(error.message);
      return [];
    }
  };

  const handleCreateCourseAppointment = async (appointment) => {
    "use server";
    delete appointment.id
    appointment.teaching_commission_rate = parseFloat(appointment.teaching_commission_rate)
    appointment.start_time = formatDateForAPI(appointment.start_time)
    appointment.end_time = formatDateForAPI(appointment.end_time)
    try {
      const newAppointment = await createCourseAppointment(appointment);
      return {
        success: true,
        data: newAppointment,
        message: "预约创建成功",
      };
    } catch (error) {
      console.error(error.message);
      return {
        success: false,
        message: error.message,
      };
    }
  };

  const handleConfirmAppointment = async (appointmentInfo) => {
    "use server";
    console.log("confirm appointment", appointmentInfo);

    const {
      course_package_ids,
      appointment_id,
      duration,
      memo
    } = appointmentInfo
    try {
      const coursePackages = course_package_ids.split(",");
      // step1 更新预约状态
      await updateCourseAppointmentStatus(appointment_id, {
        status: "inactive",
        memo,
      });
      // step2 更新客户课时
      for (const course_package_id of coursePackages) {
        await deductCoursePackageClasses(course_package_id, {
          count: parseFloat(duration),
        });
      }
      // step3 更新教练提成 ?TODO

    return {
      success: true,
        message: "预约已确认",
      };
    } catch (error) {
      console.error(error.message);
      return {
        success: false,
        message: error.message,
      };
    }
  };

  // 取消预约
  const handleCancelAppointment = async (appointmentInfo) => {
    "use server";
    const { appointment_id } = appointmentInfo
    try {
      await updateCourseAppointmentStatus(appointment_id, {
        status: "cancelled",
      });
      return {
        success: true,
        message: "预约已取消",
      };
    } catch (error) {
      console.error(error.message);
      return {
        success: false,
        message: error.message,
      };
    }
  };

  // 添加助教
  async function addAssistantCoach(formData) {
    'use server'
    try {
      const appointmentId = formData.get('appointment_id')
      const coachId = formData.get('coach_id')
      const rate = parseFloat(formData.get('teaching_commission_rate'))

      await addCourseAppointmentAssistantCoach(appointmentId, {
        coach_id: coachId,
        teaching_commission_rate: rate,
      })

      return { success: true, message: '助教添加成功' }
    } catch (error) {
      return { success: false, message: error.message }
    }
  }

  // 删除助教
  async function removeAssistantCoach(formData) {
    'use server'
    try {
      const appointmentId = formData.get('appointment_id')
      const coachId = formData.get('coach_id')

      await removeCourseAppointmentAssistantCoach(appointmentId, coachId)

      return { success: true, message: '助教删除成功' }
    } catch (error) {
      return { success: false, message: error.message }
    }
  }

  // 添加学员和课程包
  async function addClientWithPackage(formData) {
    'use server'
    try {
      const appointmentId = formData.get('appointment_id')
      const clientId = formData.get('client_id')
      const packageId = formData.get('package_id')

      // 先添加学员
      await addCourseAppointmentClient(appointmentId, {
        client_id: clientId,
      })

      // 再添加课程包
      await addCourseAppointmentPackage(appointmentId, {
        course_package_id: packageId,
        status: 'active',
        memo: ''
      })

      return { success: true, message: '学员和课程包添加成功' }
    } catch (error) {
      return { success: false, message: error.message }
    }
  }

  // 删除学员和课程包
  async function removeClientWithPackage(formData) {
    'use server'
    try {
      const appointmentId = formData.get('appointment_id')
      const clientId = formData.get('client_id')
      const packageId = formData.get('package_id')

      console.log('删除学员和课程包', appointmentId, clientId, packageId)

      // 先删除课程包
      await removeCourseAppointmentPackage(appointmentId, packageId)

      // 再删除学员
      await removeCourseAppointmentClient(appointmentId, clientId)

      return { success: true, message: '学员和课程包删除成功' }
    } catch (error) {
      return { success: false, message: error.message }
    }
  }

  return (
    <Client
      campuses={campuses}
      statuses={STATUS}
      getCourts={getCourts}
      getAllUsers={getAllUsers}
      listAppointments={listAppointments}
      confirmAppointment={handleConfirmAppointment}
      cancelAppointment={handleCancelAppointment}
      createCourseAppointment={handleCreateCourseAppointment}
      addAssistantCoach={addAssistantCoach}
      removeAssistantCoach={removeAssistantCoach}
      addClientWithPackage={addClientWithPackage}
      removeClientWithPackage={removeClientWithPackage}
      getCoursePackages={getCoursePackages}
    />
  );
}
